<?

if (empty($_SERVER['DOCUMENT_ROOT'])) {
        $_SERVER['DOCUMENT_ROOT'] = "/var/www/vhosts/geographs.org/httpdocs/";
}


include($_SERVER['DOCUMENT_ROOT'].'/includes/functions.inc.php');
include($_SERVER['DOCUMENT_ROOT'].'/portals/config.php');
include($_SERVER['DOCUMENT_ROOT'].'/groups/database.php');

if (false) {
	init_session();

	if (empty($_SESSION['user_id'])) {
		include($_SERVER['DOCUMENT_ROOT'].'/portals/login.inc.php');
		exit;
	}
}

############################

define('MAX_WORDS', 100);
define('MAX_WORD_LENGTH', 10);


queryExecute("TRUNCATE libpuzzleword");
queryExecute("ALTER TABLE libpuzzleword DISABLE KEYS");

queryExecute("TRUNCATE libpuzzlesig");


print "Opening file...\n";

$h = fopen('libpuzzle-out.txt','r');

$s = $w = 0;

while (!feof($h)) {
	$line = fgets($h);
	$bits = explode("\t",trim($line),2);

	if (strlen($bits[1]) > 500 && $bits[0]) {

		$sql = "INSERT IGNORE INTO libpuzzlesig SET gridimage_id = $bits[0], sig = ".dbQuote($bits[1]);
		queryExecute($sql);

		if (mysql_affected_rows() > 0) {
			$words = split_into_words($bits[1]);
			foreach ($words as $u => $word) {
				$sql =  "INSERT IGNORE INTO libpuzzleword SET gridimage_id = $bits[0], `word` = CRC32(".dbQuote(chr($u). $word).")";
				queryExecute($sql);
				$w++;
			}
		}
	}
	$s++;
	if (!($s%1000)) {
		print "done $s with $w\n";
	}
}

print "Enabling Keys...\n";

queryExecute("ALTER TABLE libpuzzleword ENABLE KEYS");

print "Done!\n";



function split_into_words($sig) {
    $words = array();
    $u = 0;
    do {
        $words[$u] = substr($sig, $u, MAX_WORD_LENGTH);
    } while (++$u < MAX_WORDS);

    return $words;
}

